package help;

import handler.DeformationPoint;
import handler.LineHandler;
import handler.PointHandler;

import java.util.Observable;
import java.util.Observer;

public class DeformationHanlderTransfare implements Observer{

	LineHandler originalPointHandler;
	LineHandler transfarePointHandler;
	int height;
	public DeformationHanlderTransfare(LineHandler originalPointHandler , int height) {
		this.height = height;
		this.originalPointHandler = originalPointHandler;
		DeformationPoint[] basePoints=originalPointHandler.getBasePointsArray();
		transform(basePoints);
		DeformationPoint[] movedPoints=originalPointHandler.getMovedPointsArray();
		transform(movedPoints);
		this.transfarePointHandler = new LineHandler(basePoints, movedPoints,originalPointHandler.getLines());
		this.originalPointHandler.addObserver(this);
		this.transfarePointHandler.addObserver(this);
	}
	
	
	public LineHandler getTransfareLineHandler(){
		return transfarePointHandler;
	}
	
	
	private void transform(DeformationPoint[] movedPoints){
		int height = this.height;
		for (int j = 0; j < movedPoints.length; j++) {
			DeformationPoint oldPoint = movedPoints[j];
			movedPoints[j] = new DeformationPoint(oldPoint.x,height- oldPoint.y);
		}
		
	}
	
	public void destroy(){
		originalPointHandler.deleteObserver(this);
		transfarePointHandler.deleteObserver(this);
		originalPointHandler = null;
		transfarePointHandler = null;
	}


	@Override
	public void update(Observable observable, Object arg) {
		PointHandler changedHandler= null;
		PointHandler toUpdate= null;
		if (observable == originalPointHandler) {
			changedHandler = originalPointHandler;
			toUpdate= transfarePointHandler;
		} else if(observable == transfarePointHandler){
			changedHandler = transfarePointHandler;
			toUpdate= originalPointHandler;
		} else{
			return;
		}
		toUpdate.deleteObserver(this);
		if (arg instanceof Integer) {
			int i = ((Integer)arg).intValue();
			DeformationPoint moved = changedHandler.getMovedPoints().get(i);
			moved = new DeformationPoint(moved.x,height- moved.y);
			toUpdate.move(i, moved);
		}else{
		DeformationPoint[] moved = changedHandler.getMovedPointsArray();
		transform(moved);
		toUpdate.moveAll(moved);
		}
		toUpdate.addObserver(this);
		
	}

}
